<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const positions = ref([])
const departments = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加岗位')
const isEdit = ref(false)
const searchQuery = ref('')
const salarySchemes = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const formRef = ref(null)
const form = reactive({
  id: null,
  name: '',
  departmentId: '',
  description: '',
  status: true,
  schemeId: null
})

const rules = {
  name: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
  departmentId: [{ required: true, message: '请选择所属部门', trigger: 'change' }]
}

// 获取岗位列表（分页）
const fetchPositions = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    if (searchQuery.value) {
      params.keyword = searchQuery.value
    }
    
    const response = await axios.get('/positions/page', { params })
    const data = response.data
    
    if (data && data.records) {
      positions.value = data.records || []
      total.value = data.total || 0
    } else {
      positions.value = []
      total.value = 0
    }
    loading.value = false
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败，请重试')
    positions.value = []
    total.value = 0
    loading.value = false
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await axios.get('/departments')
    departments.value = response.data
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败，请重试')
  }
}

// 获取薪资方案列表
const fetchSalarySchemes = async () => {
  try {
    const response = await axios.get('/salary/schemes')
    salarySchemes.value = response.data || []
  } catch (error) {
    ElMessage.error('获取薪资方案失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPositions()
}

// 清空搜索
const handleClearSearch = () => {
  searchQuery.value = ''
  currentPage.value = 1
  fetchPositions()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchPositions()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchPositions()
}

// 打开添加岗位对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '添加岗位'
  form.id = null
  form.name = ''
  form.departmentId = ''
  form.description = ''
  form.status = true
  form.schemeId = null
  dialogVisible.value = true
}

// 打开编辑岗位对话框
const openEditDialog = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑岗位'
  form.id = row.id
  form.name = row.name
  form.departmentId = row.departmentId
  form.description = row.description || ''
  form.status = row.status
  form.schemeId = row.schemeId || null
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const payload = {
          name: form.name,
          departmentId: form.departmentId,
          description: form.description,
          status: form.status,
          schemeId: form.schemeId
        }
        
        if (isEdit.value) {
          await axios.put(`/positions/${form.id}`, payload)
          ElMessage.success('岗位更新成功')
        } else {
          await axios.post('/positions', payload)
          ElMessage.success('岗位添加成功')
        }
        
        fetchPositions()
        dialogVisible.value = false
      } catch (error) {
        console.error('提交岗位信息失败:', error)
        if (error.response && error.response.data) {
          ElMessage.error(`提交失败: ${error.response.data.message || error.message}`)
        } else {
          ElMessage.error(`提交失败: ${error.message}`)
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除岗位
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除岗位"${row.name}"吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await axios.delete(`/positions/${row.id}`)
      ElMessage.success('岗位删除成功')
      fetchPositions()
    } catch (error) {
      console.error('删除岗位失败:', error)
      if (error.response && error.response.data) {
        ElMessage.error(`删除失败: ${error.response.data.message || error.message}`)
      } else {
        ElMessage.error('删除失败，请重试')
      }
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 切换岗位状态
const handleToggleStatus = async (row) => {
  try {
    loading.value = true
    await axios.put(`/positions/${row.id}/toggle-status`)
    ElMessage.success(`岗位已${row.status ? '禁用' : '启用'}`)
    fetchPositions()
  } catch (error) {
    console.error('切换岗位状态失败:', error)
    if (error.response && error.response.data) {
      ElMessage.error(`操作失败: ${error.response.data.message || error.message}`)
    } else {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 根据部门ID获取部门名称
const getDepartmentName = (departmentId) => {
  const department = departments.value.find(dept => dept.id === departmentId)
  return department ? department.name : '未知部门'
}

// 根据薪资方案ID获取薪资方案名称
const getSchemeName = (schemeId) => {
  const scheme = salarySchemes.value.find(s => s.id === schemeId)
  return scheme ? scheme.name : '未分配'
}

onMounted(() => {
  fetchPositions()
  fetchDepartments()
  fetchSalarySchemes()
})
</script>

<template>
  <div class="position-container">
    <div class="page-header">
      <div class="page-title">岗位管理</div>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索岗位名称或描述"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleClearSearch"
          style="width: 250px; margin-right: 15px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button 
          type="primary" 
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button 
          type="primary" 
          @click="openAddDialog"
          style="margin-left: 10px;"
        >
          <el-icon><Plus /></el-icon>添加岗位
        </el-button>
      </div>
    </div>
    
    <div class="table-container">
      <el-table 
        :data="positions" 
        border 
        style="width: 100%" 
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="岗位名称" width="150" />
        <el-table-column label="所属部门" width="150">
          <template #default="{ row }">
            {{ row.departmentName || getDepartmentName(row.departmentId) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="岗位描述" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.createTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="openEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button 
              :type="row.status ? 'warning' : 'success'" 
              size="small" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑岗位对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入岗位名称" />
        </el-form-item>
        
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择所属部门" style="width: 100%">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="岗位描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            rows="3"
            placeholder="请输入岗位描述"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="true"
            :inactive-value="false"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        
        <el-form-item label="薪资方案">
          <el-select v-model="form.schemeId" placeholder="请选择薪资方案" clearable filterable>
            <el-option v-for="item in salarySchemes" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.position-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
}

.table-container {
  flex: 1;
  padding: 0 20px 20px;
  background-color: #fff;
  overflow-y: auto;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  background-color: #fff;
}

/* 调整表格行高 */
:deep(.el-table__row) {
  height: 50px;
}

/* 调整表格头部样式 */
:deep(.el-table__header) {
  font-weight: bold;
  background-color: #f5f7fa;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f0f8ff !important;
}
</style> 